package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import com.sun.org.apache.bcel.internal.generic.GETFIELD;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController {

    @Autowired
    ISysDictTypeService sysDictTypeService;

    @Autowired
    ISysUserService sysUserService;


    @GetMapping("/list")
    public TableDataInfo selectAll(SysDictType sysDictType){
        startPage();
        List<SysDictType>list=sysDictTypeService.selectDictType(sysDictType);
        return getDataTable(list);
    }

    @DeleteMapping("/{dictId}")
    public int deleteDictId(@PathVariable(value = "dictId",required = false)Long[] dictId){
        int cn=sysDictTypeService.deleteDictType(dictId);
        return cn;
    }

    @PostMapping("/add")
    public int insertDictType(@Validated @RequestBody SysDictType sysDictType){
        SysUser sysUser=sysUserService.selectuserId(getUserId());
        sysDictType.setCreateBy(sysUser.getUserName());
        sysDictType.setCreateTime(new Date());
        int cn=sysDictTypeService.insertiDictType(sysDictType);
        return 1;
    }

    @GetMapping("/{dictId}")
    public SysDictType selectDictDancha(@PathVariable(value = "dictId",required = false) Long dictId){
        SysDictType sysDictType=sysDictTypeService.selectDictDancha(dictId);
        return sysDictType;
    }

    @PutMapping("/update")
    public int updateDictType(@Validated  @RequestBody SysDictType sysDictType){
        int cn=0;
        SysUser sysUser=sysUserService.selectuserId(getUserId());
        SysDictType sysDictType1=sysDictTypeService.selectDictDancha(sysDictType.getDictId());
        if (sysDictType.getDictType().equals(sysDictType1.getDictType())){
            sysDictType.setDictType(sysDictType1.getDictType());
            sysDictType.setUpdateBy(sysUser.getUserName());
            sysDictType.setUpdateTime(new Date());

            cn=sysDictTypeService.updateDict(sysDictType);
            return cn;
        }else {
            if (sysDictTypeService.selecDictNameCount(sysDictType.getDictType())>0){
                cn=0;
                return cn;
            }
        }
        return cn;
    }
}
